package com.ipzoe.app.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ipzoe.app.core.config.WxMaConfiguration;
import com.ipzoe.app.core.exception.ServiceException;
import com.ipzoe.app.core.response.ApiResponseData;
import com.ipzoe.app.core.response.SuccessApiResponseData;
import com.ipzoe.common.core.domain.AjaxResult;
import com.ipzoe.common.exception.CustomException;
import com.ipzoe.mem.domain.WechatUser;
import com.ipzoe.mem.service.IWechatUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

@RestController
@RequestMapping("/api/v1/wx")
@Api(tags = "微信相关接口")
@Validated
@Slf4j
public class WeixinController {

    @Autowired
    private IWechatUserService wechatUserService;

    @ApiOperation("微信小程序登录")
    @GetMapping("/ma/login")
    @ApiImplicitParam(name = "code", value = "微信授权获取的code", required = true, dataType = "string")
    public AjaxResult login(@NotBlank(message = "微信授权获取的code不能为空") @RequestParam String code) {

        final WxMaService wxService = WxMaConfiguration.getMaService();

        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            return AjaxResult.success(session);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return AjaxResult.error(400,"授权失败");
        }

    }

}
